import { forwardRef, Inject, Injectable } from '@nestjs/common';

import {
  SubscribeMessage,
  WebSocketGateway,
  MessageBody,
  ConnectedSocket,
  WebSocketServer,
} from '@nestjs/websockets';
import { Socket } from 'socket.io';
import { User } from 'src/entities/user.entity';
import { AddFriendDto } from 'src/friend-application/dto/add-friend.dto';
import { FriendApplicationService } from 'src/friend-application/friend-application.service';
import { FriendService } from 'src/friend/friend.service';
import { UserMessageService } from 'src/user-message/user-message.service';

interface messageInterface {}

interface socketAuthList {
  socketId: string;
  userId: string;
}

let list: socketAuthList[] = [];

@WebSocketGateway({
  cors: true,
})
@Injectable()
export class SocketService {
  constructor(
    private readonly friendService: FriendService,
    @Inject(forwardRef(() => UserMessageService))
    private readonly userMessageService: UserMessageService,
    @Inject(forwardRef(() => FriendApplicationService))
    private readonly friendApplicationService: FriendApplicationService,
  ) {}
  // handleConnection(socket: Socket, @MessageBody() data: string) {
  //   console.log(socket.id);
  // }

  @WebSocketServer()
  server: Socket;

  @SubscribeMessage('init')
  async handleEvent(
    @MessageBody('userId') userId: string,
    @ConnectedSocket() client: Socket,
  ) {
    const index = list.findIndex((item) => item.userId == userId);
    if (index != -1) {
      list = list.map((item) => {
        if (item.userId == userId) {
          item.socketId = client.id;
        }
        return item;
      });
    } else {
      list.push({
        socketId: client.id,
        userId,
      });
    }
    let userApprove = await this.friendApplicationService.findAll(userId);
    let getMessageUserList = await this.userMessageService.getMessageUserList(
      userId,
    );
    this.server.to(client.id).emit('getUserApprove', userApprove);
    this.server.to(client.id).emit('getMessageUserList', getMessageUserList);
  }

  sendNewUser(userId: string, user: User) {
    const index = list.findIndex((item) => item.userId == userId);
    if (index == -1) return;
    this.server.to(list[index].socketId).emit('newUser', user);
  }

  sendNewUserApprove(userId: string, userApprove: any) {
    const index = list.findIndex((item) => item.userId == userId);
    if (index == -1) return;
    this.server.to(list[index].socketId).emit('newUserApprove', userApprove);
  }

  sendNewMessage(userId: string, friend: User, message: any) {
    const index = list.findIndex((item) => item.userId == userId);
    if (index == -1) return;
    this.server
      .to(list[index].socketId)
      .emit('sendNewMessage', friend, message);
  }

  handleDisconnect(socket: Socket) {
    const index = list.findIndex((item) => item.socketId == socket.id);
    if (index != -1) list.splice(index, 1);
    console.log(socket.id + '销毁了');
  }
}
